package com.my.mymafengwo.base;

import android.media.MediaPlayer;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

/**
 * ***********************************************
 * author:wgh
 * time:2015/12/1 19:44
 * copyright:
 * name:
 * step:
 * ***********************************************
 */
public abstract class WithMediaPlayerActivity extends BaseActivity implements SurfaceHolder.Callback, MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener {

    private MediaPlayer mediaPlayer;
    private SurfaceHolder holder;

    /**
     * 加载资源文件中的视频时使用的播放器
     *
     * @param surfaceView 加载视频的布局
     * @param resId       资源id
     */
    protected void playMedia(SurfaceView surfaceView, int resId) {
        if (mediaPlayer == null) {
            //创建播放器对象
            //此方法在装载完成时即完成prepare
            mediaPlayer = MediaPlayer.create(this, resId);
        }
        initHolder(surfaceView);
    }

    /**
     * 初始化holder对象
     *
     * @param surfaceView
     */
    private void initHolder(SurfaceView surfaceView) {
        //给surfaceView添加CallBack监听
        holder = surfaceView.getHolder();
        holder.addCallback(this);
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

        setListener();
    }

    /**
     * 给播放器设置监听
     */
    private void setListener() {
        mediaPlayer.setOnPreparedListener(this);
        mediaPlayer.setOnCompletionListener(this);
    }

    /**
     * 停止视频播放
     */
    protected void stopMedia() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {

    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

        // 当SurfaceView中的Surface被创建的时候被调用
        //在这里我们指定MediaPlayer在当前的Surface中进行播放
        mediaPlayer.setDisplay(holder);
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {

    }

    /**
     * 视频播放完成
     *
     * @param mp
     */
    @Override
    public void onCompletion(MediaPlayer mp) {
        if (mp != null) {
            mediaPlayer = null;
        }
    }

    /**
     * 播放器准备完成
     *
     * @param mp
     */
    @Override
    public void onPrepared(MediaPlayer mp) {
        //开始播放视频
        mp.start();
    }

    /**
     * 调整音量
     *
     * @param leftVolume
     * @param rightVolume
     */
    protected void turnMusic(float leftVolume, float rightVolume) {
        if (mediaPlayer != null) {
            mediaPlayer.setVolume(leftVolume, rightVolume);
        }
    }


}
